<template>
  <div class="bodys">
    <div>
      <div class="selection">
        <h4>闭式冷却塔-选型程序</h4>
        <div class="btn">
          <el-button
            type="primary"
            @click="getSelect(indexs)"
            icon="el-icon-setting"
            :loading="loading"
            >自动选型</el-button
          >
          <!-- <el-dropdown
            split-button
            type="primary"
            trigger="click"
            @click="getSelect"
            :loading="loading"
            icon="el-icon-setting"
          >
            
            自动选型
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in menuList"
                :key="index"
                :command="item.categoryIndex"
                @click.native="getSelect(item.categoryIndex)"
                >{{ item.categoryName }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown> -->
          <el-button
            type="primary"
            @click="systemopen"
            icon="el-icon-download"
            :disabled="disabled"
            >下载报告</el-button
          >
        </div>
      </div>
      <div class="content">
        <div class="content1">
          <el-form :label-position="labelPosition" label-width="220px">
            <el-form-item label="Water Flow (循环水量) m3/h">
              <el-input-number :min="0" v-model="ruleForm.waterflow" />
              <span class="sins" v-if="!isshow">660GPM</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c5cc) }}{{ listReport.c5IUM }}</span
              >
            </el-form-item>
            <el-form-item label="Hot Water Temp (进水温度) ℃">
              <el-input-number :min="0" v-model="ruleForm.hotwater" :max="60" />
              <span class="sins" v-if="!isshow">98℉</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c6cc) }}{{ listReport.c6IUM }}</span
              >
            </el-form-item>
            <el-form-item label="Cold Water Temp(出水温度) ℃">
              <el-input-number :min="0" v-model="ruleForm.coldwater" />
              <span class="sins" v-if="!isshow">89℉</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c7cc) }}{{ listReport.c7IUM }}</span
              >
            </el-form-item>
            <el-form-item label="Wet Bulb Temp (湿球温度) ℃">
              <el-input-number :min="12" :max="32" v-model="ruleForm.wet" />
              <span class="sins" v-if="!isshow">66℉</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c8cc) }}{{ listReport.c8IUM }}</span
              >
            </el-form-item>
            <el-form-item label="Heat Rejection (热负荷) kcal/hr">
              <el-input
                type="number"
                style="width: 63%"
                v-model="listReport.c9"
                disabled
              />
              <span class="sins" v-if="!isshow">0kw</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c9cc) }}{{ listReport.c9IUM }}</span
              >
            </el-form-item>
            <el-form-item label="RANGE (温降) ℃">
              <el-input
                type="number"
                style="width: 63%"
                v-model="listReport.c10"
                disabled
              />
              <span class="sins" v-if="!isshow">0℉</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c10cc) }}{{ listReport.c10IUM }}</span
              >
            </el-form-item>
            <el-form-item label="APPROCH(逼近度) ℃">
              <el-input
                type="number"
                style="width: 63%"
                v-model="listReport.c11"
                disabled
              />
              <span class="sins" v-if="!isshow">0℉</span>
              <span class="sins" v-if="isshow"
                >{{ parseInt(listReport.c11cc) }}{{ listReport.c11IUM }}</span
              >
            </el-form-item>
          </el-form>
        </div>

        <div class="content2">
          <el-form :label-position="labelPosition" label-width="250px">
            <!-- <el-form-item label="Water-Air Ratio L/G (水气比)">
              <el-input
                type="number"
                placeholder="请输入地址！"
                style="width: 93%"
                v-model="ruleForm.waterair"
                disabled
              />
            </el-form-item>
            <el-form-item label="Rating Factor(选定系数)">
              <el-input
                type="number"
                placeholder="请输入地址！"
                style="width: 93%"
                v-model="ruleForm.rating"
                disabled
              />
            </el-form-item> -->
            <el-form-item label="相当参考标准点的冷却能力m3/h">
              <el-input
                type="number"
                style="width: 93%"
                v-model="listReport.c14"
                disabled
              />
            </el-form-item>
            <el-form-item label="系统推荐使用型号标准能力m3/h">
              <el-input
                type="number"
                style="width: 93%"
                v-model="listReport.c15"
                disabled
              />
            </el-form-item>
            <el-form-item label="Select Reserve (所选型号裕量) %">
              <el-input
                type="number"
                style="width: 93%"
                v-model="listReport.c16"
                disabled
              />
            </el-form-item>
            <el-form-item label="Equipment Type(设备类型)">
              <!-- <el-dropdown split-button type="primary" :loading="loading">
                {{ this.indexs }}
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="item in menuList"
                    :key="item.categoryIndex"
                    :command="item.categoryIndex"
                    @click.native="rowClick(item.categoryIndex, $event)"
                    >{{ item.categoryName }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown> -->
              <el-select v-model="indexs" placeholder="请选择设备类型">
                <el-option
                  v-for="item in menuList"
                  :key="item.categoryIndex"
                  :label="item.categoryName"
                  :value="item.categoryIndex"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="Select Model (选定冷却塔型号)" class="inputs">
              <el-input
                type="text"
                style="width: 93%"
                v-model="listReport.selectedFBSModel"
                disabled
              />
            </el-form-item>
            <el-form-item class="inputs">
              <el-input
                type="text"
                style="width: 93%"
                v-model="listReport.selectedModel"
                disabled
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 打印报告 -->
    <el-dialog
      :visible.sync="open"
      width="80%"
      append-to-body
      @close="closeDialog"
    >
      <!-- 头部 -->
      <div class="frame" id="frame">
        <table>
          <tr>
            <td><img src="../../public/images/404/fbss.png" alt="" /></td>
            <td>
              <p>冷却塔计算书</p>
              <p>COOLING TOWER DESIGN DATA</p>
            </td>
            <td>
              <p>MESSRS:</p>
              <p><nowtime /></p>
            </td>
          </tr>
        </table>
      </div>
      <div class="more" id="more">
        <!-- 机型 -->
        <div class="morelit">
          <table>
            <tr>
              <td>
                <div v-html="reportContent.contents"></div>
              </td>
              <td valign="top">
                <img
                  :src="`https://phoebus-tenant-1.oss-cn-shanghai.aliyuncs.com/${reportContent.drawFile}`"
                  alt=""
                  style="width: 300px"
                />
              </td>
            </tr>
          </table>
          <span> 单台处理水量:{{ this.c5 }}m³/h</span>
          <span> 进出水温度:{{ this.c6 }}-{{ this.c7 }}°C</span>
          <span> 参考值:37-32°C/28</span>
          <span> 湿球温度:{{ this.c8 }}°C</span>
          <div id="chart" style="margin-top: -30px">
            <LineChart
              :parentC5="this.c5"
              :parentC15="this.c15"
              :parentC14="this.c14"
              :parentC8="this.c8"
              :parentC6="this.c6"
              :parentC7="this.c7"
              :datax="this.result.x"
              :datay="this.result.y2"
              :datac="this.result.y"
              :dataz="this.result.z"
              @imgs="getimg"
            />
          </div>
          <!-- <p>机型Model:{{ reportContent.f_Model }}</p> -->
        </div>
      </div>
      <div class="more" id="more2" v-show="false">
        <div v-html="reportContent.contents"></div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="exportWord">下载报告</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import LineChart from "@/components/LineChart.vue";
import { autoSelect, getReport, getMenu } from "../api/login/index";
// import { downloadTxt } from "../api/login/reporttitle";
import nowtime from "../components/nowTime.vue";
import FileSaver from "file-saver";
import htmlDocx from "html-docx-js/dist/html-docx";
// import docxtemplater from "docxtemplater";
// import JSZipUtils from "jszip-utils";
import { chart } from "../api/login/reporttitle";

// import PizZip from "pizzip";
export default {
  inject: ["reload"],
  components: {
    LineChart,
    nowtime,
  },
  data() {
    return {
      disabled: true,
      isshow: false,
      isshows: false,
      loading: false,
      isdownload: false,
      // 自动选型
      listReport: {},
      poolType: "0",
      //选型菜单
      menuList: [],
      indexs: "",
      index: "",
      // 报告内容
      reportContent: {},
      // 报告下载内容
      text: {},
      labelPosition: "right",
      ruleForm: {
        waterflow: "100",
        hotwater: "37",
        coldwater: "32",
        wet: "28",
        heat: "",
        range: "",
        approch: "",
        waterair: "",
        rating: "",
        cold: "",
        system: "",
        select: "",
        model: "",
        models: "",
      },
      open: false,
      parentImg: "",
      c5: 0,
      c6: 0,
      c7: 0,
      c15: 0,
      c14: 0,
      c8: 0,
      result: [],
      current: [],
    };
  },

  created() {},
  mounted() {
    getMenu("EquClass", "0", "10").then((res) => {
      this.menuList = res.result.items;
      if (this.menuList.length > 0) {
        this.indexs = this.menuList[0].categoryIndex;
      }
    });
  },
  watch: {
    //监听子组件传值
    img(newValue, oldValue) {
      console.log("新的", newValue);
      this.getimg(newValue);
    },
  },
  methods: {
    rowClick: function (index, event) {
      this.indexs = index; // 点击时，切换选中索引
    },

    getSelect(item) {
      // this.$message("click on item " + item);
      this.index = item;
      this.loading = true;
      console.log(this.ruleForm);

      // return;
      autoSelect(
        this.index,
        this.ruleForm.waterflow,
        this.ruleForm.hotwater,
        this.ruleForm.coldwater,
        this.ruleForm.wet
      ).then((response) => {
        // console.log(this.c5);
        console.log(response.result);

        chart(
          this.ruleForm.waterflow,
          this.ruleForm.hotwater,
          this.ruleForm.coldwater,
          this.ruleForm.wet
        ).then((res) => {
          this.result = res.result;

          for (var i = 0; i < this.result.y.length; i++) {
            if (this.result.y[i] == "Infinity") {
              this.result.y[i] = undefined;
            } else {
              this.result.y[i] = this.result.y[i].toFixed(2);
            }
            if (this.result.y2[i] == "Infinity") {
              this.result.y2[i] = undefined;
            } else {
              this.result.y2[i] = this.result.y2[i].toFixed(2);
            }

            // this.result.z[i] = this.result.z[i].toFixed(2);
            // console.log(this.result.z[i]);
          }

          this.listReport = response.result;
          console.log("123", this.listReport);
          this.ruleForm.models = response.result.selectedModel;
          this.ruleForm.model = response.result.selectedFBSModel;
          console.log(this.ruleForm.models);
          // if (this.ruleForm.hotwater > 60) {
          //   this.$message({
          //     type: "warning",
          //     message: "进水温度不能大于60℃",
          //   });
          //   this.loading = false;
          //   this.disabled = false;
          //   return;
          // }
          if (this.ruleForm.models == null) {
            this.$message({
              type: "warning",
              message: "没有匹配的设备,请重新选型",
            });
          } else {
            this.$message({
              type: "success",
              message: "设备匹配成功",
            });
          }
          if (this.listReport.c16 == "NaN") {
            this.listReport.c16 = undefined;
          } else {
            this.listReport.c16 = this.listReport.c16.toFixed(2);
          }

          if (this.listReport.c14 == "Infinity") {
            this.listReport.c14 = undefined;
          } else {
            this.listReport.c14 = this.listReport.c14.toFixed(2);
          }

          this.isshow = true;
          this.c5 = this.listReport.c5;
          this.c15 = this.listReport.c15;
          this.c8 = this.listReport.c8;
          this.c6 = this.listReport.c6;
          // console.log(this.listReport);
          this.c7 = this.listReport.c7;
          this.c14 = this.listReport.c14;

          this.loading = false;
          this.disabled = false;
        });
      });
    },
    // 导出echarts图片，格式转换
    base64DataURLToArrayBuffer(dataURL) {
      console.log(dataURL, "dataURL");
      debugger;
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },

    exportWord() {
      this.isshows = true;
      //将本地图片转换成base64,才能下载
      // var canvas = document.createElement("canvas");
      // var ctx = canvas.getContext("2d");
      // // canvas.width = 77;
      // // canvas.height = 25;
      // ctx.drawImage(this.$refs.image, 0, 0, 269, 34);
      // let image = new Image();
      // //require
      // image.src = canvas.toDataURL("image/png", 1);
      // console.log(image.src);

      setTimeout(() => {
        let contentHtml = document.getElementById("more2").innerHTML;

        let cssHTML = `
          table{
          width: 100%;
          height:100%
          text-align:center;
          }
          td {
          font-size:12px;
          text-align: left;
          padding: 6px 10px;
          border: 0px;
          }
          img{
            padding:0 0;
          }
          `;
        let fbsImg = `<img src="http://121.41.14.139:8007/static/img/fbs.2a8995d2.png" alt="" width="170" height="60"/>`;
        let img = `<img src="${this.parentImg}" alt="" width="700" height="326" />`;
        let prdImg = `<img src="https://phoebus-tenant-1.oss-cn-shanghai.aliyuncs.com/${this.reportContent.drawFile}"  width="133" height="180"/>`;
        console.log("图", prdImg);
        const date = new Date();
        const dateStr =
          date.getFullYear() +
          "-" +
          (parseInt(date.getMonth()) + 1).toString() +
          "-" +
          date.getDate();
        let content = `
         	<!DOCTYPE html><html>
              	<head>
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                    <style>
                        ${cssHTML}
                    </style>
                </head>
                <body>
                    <table>
                    <tr>
                    <td>
                        <div><b>${fbsImg}</b></div>
                        </td>
                        <td>
                        <div style="font-size:18;font-weight:600"><b>专注于换热设备研发制造与服务</b></div>
                        </td>
                    </tr>
                      <tr>
                      <td>
                    		<div>
                        <b>冷却塔计算书</b>
                        </div>
                        <div><b>COOLING TOWER DESIGN DATA</div>
                        </td>
                        <td><div><b>MESSRS:</b></div>
                        <div><b>DATA: ${dateStr}</b></div></td>
                        <td>${prdImg}</td>
                      </tr>
                  	</table>
                    ${contentHtml}
                    <p style="font-size:12;">单台处理水量:${this.c5}m³/h 进出水温度:${this.c6}-${this.c7}°C 参考值:37-32°C/28 湿球温度:${this.c8}°C</p>
                    <div>${img}</div>
                </body>
              </html>`;
        let converted = htmlDocx.asBlob(content);
        FileSaver.saveAs(converted, "选型配置.docx");
        this.open = false;
        // this.reload();
      }, 2000);
    },
    // 获取折线图地址
    getimg(img) {
      this.parentImg = img;
      // console.log("子地址", this.parentImg);
    },
    // 取消下载
    cancel() {
      this.open = false;
      // this.reload();
    },
    // dialog关闭事件
    closeDialog() {
      // this.reload();
    },
    // 打印报告弹框
    systemopen() {
      const h = this.$createElement;
      this.$msgbox({
        title: "选型报告",
        message: h("p", null, [
          h("span", null, "您的选型报告已经生成,确定立即查看? "),
          h("i", { style: "color: teal" }, ""),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "正在生成报告...";
            getReport(
              this.listReport.equipmentId,
              this.listReport.c5,
              this.listReport.c6,
              this.listReport.c7,
              this.listReport.c8
            ).then((response) => {
              this.reportContent = response.result;
              this.reportContent.f_Model = this.ruleForm.models;
              instance.confirmButtonText = "确定";
              instance.confirmButtonLoading = false;
              console.log("获取", this.reportContent);
              console.log("获取2", response.result);
              this.open = true;
              done();
            });
          } else {
            done();
          }
        },
      })
        .then(() => {
          this.$message({
            type: "info",
            message: "报告生成成功",
          });
          this.open = true;
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消报告生成" : "停留在当前页面",
          });
          this.reload();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../public/styles/index.scss";
</style>
